package com.ittao.taopicture.interfaces.controller;

import com.ittao.taopicture.infrastructure.annotation.AuthCheck;
import com.ittao.taopicture.infrastructure.common.BaseResponse;
import com.ittao.taopicture.infrastructure.common.ResultUtils;
import com.ittao.taopicture.domain.user.constant.UserConstant;
import com.ittao.taopicture.infrastructure.exception.BusinessException;
import com.ittao.taopicture.infrastructure.exception.ErrorCode;
import com.ittao.taopicture.infrastructure.api.cos.CosManagerApi;
import com.qcloud.cos.model.COSObject;
import com.qcloud.cos.model.COSObjectInputStream;
import com.qcloud.cos.utils.IOUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;

@RestController
@RequestMapping("/file")
@Slf4j
public class FileController {

    @Resource
    private CosManagerApi cosManagerApi;

    /**
     * 测试文件上传
     *
     * @param multipartFile 文件
     * @return
     */
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @PostMapping("/test/upload/")
    public BaseResponse<String> testUploadFile(@RequestPart("file") MultipartFile multipartFile) {
        // 文件目录
        String filename = multipartFile.getOriginalFilename();
        String filePath = String.format("test/%s", filename);

        File file = null;
        try {
            // 上传文件
            file = File.createTempFile(filePath, null);
            multipartFile.transferTo(file);
            // 上传到腾讯云COS
            cosManagerApi.putObject(filePath, file);
            // 返回可访问的地址
            return ResultUtils.success(filePath);
        } catch (IOException e) {
            log.error("文件上传失败,filePath = {}", filePath, e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "文件上传失败，请稍后重试");
        } finally {
            if (file != null) {
                // 删除临时文件
                if (!file.delete()) {
                    log.warn("临时文件删除失败，filePath = {}", filePath);
                }
            }
        }
    }

    /**
     * 测试文件下载
     *
     * @param filePath 文件路径
     * @return response 响应v
     */
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @GetMapping("/test/download/")
    public void testDownloadFile(String filePath, HttpServletResponse response) throws IOException {
        COSObjectInputStream cosObjectInput = null;
        try {
            COSObject cosObject = cosManagerApi.getObject(filePath);
            cosObjectInput = cosObject.getObjectContent();
            byte[] bytes = IOUtils.toByteArray(cosObjectInput);
            // 设置相应头
            response.setContentType("application/octet-stream;charset=utf-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + filePath);
            // 写入相应
            response.getOutputStream().write(bytes);
            response.getOutputStream().flush();
        } catch (IOException e) {
            log.error("文件下载失败,filePath = {}", filePath, e);
            throw new RuntimeException(e);
        } finally {
            // 关闭流
            if (cosObjectInput != null) {
                cosObjectInput.close();
            }
        }
    }
}
